package com.dream.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLClassLoader;

import javax.persistence.GeneratedValue;

import org.hibernate.annotations.GenericGenerator;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.StringMemberValue;

@SuppressWarnings("all")
public class BuildEntityClass {

	public static Class<?> getBuildClass(String basePath,String className,String basePack){
		try{
			String javaPackageName = (basePack+"."+className).replace(".",File.separator)+".java";
	        String javaAbsolutePath = basePath+"/src/"+javaPackageName;
	        String allIdPtah = basePath+"/src/"+(basePack+"."+"AllId").replace(".",File.separator)+".java";;
	        System.out.println("javaAbsolutePath:"+javaAbsolutePath);
	        String javaJdkPath = System.getenv("JAVA_HOME") + "\\bin\\";
	        Process process = Runtime.getRuntime().exec(javaJdkPath+"javac -cp"+ " " + basePath+"\\WebContent\\WEB-INF\\classes\\*;"
	        			+ basePath + "\\WebContent\\WEB-INF\\lib\\*"+ " " +allIdPtah + " " + javaAbsolutePath);
	        try {
	        	
	            InputStream errorStream = process.getErrorStream();
 	            InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
	            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  	            String line = null;
  	            
	            while ((line=bufferedReader.readLine()) != null){
	                System.out.println(line);
	            }
	            
	            int exitVal = process.waitFor();
	            
	            String classPath = basePath+"/src";
	            System.out.println(classPath);
	            URL url = new URL("file:/"+classPath+"/");
	            System.out.println("url:"+url);
	            URLClassLoader classsLoader = new URLClassLoader(new URL[]{url});
	            return classsLoader.loadClass(basePack+"."+className);
	            
	           /* String javaClassPath =  basePath+"/src/" + (basePack+"."+className).replace(".",File.separator)+".class";
	            return addClassAnnontions(className, basePack, javaClassPath);*/
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        }
	    	return null;
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("编译实体类失败!");
		}
		return null;
	}
}
